package T01_JDBC的核心API;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 1.Insert 插入数据（向学生表中添加4条记录,主键是自增长）
 */
public class T02_InsertTest {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;
        try {

            //0.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //1.创建连接对象 协议:子协议://主机:端口/数据库?usessl=false
             connection = DriverManager.getConnection("jdbc:mysql://localhost:3309/test?useSSL=false","root", "root");

            //2.通过连接对象 创建 Statement 语句对象
             statement = connection.createStatement();

            //3. 执行 SQL 语句：executeUpdate(sql)
            int count=0;

            //4. 执行 SQL
            count+=statement.executeUpdate("insert into `user` values(null, '雷神', '12345', '邯郸市邯山区邯郸大学','15630051326')");
            count+=statement.executeUpdate("insert into `user` values(null, '孙悟空', '12345', '邯郸市邯山区邯郸大学','15630051326')");
            count+=statement.executeUpdate("insert into `user` values(null, '白骨精', '12345', '邯郸市邯山区邯郸大学','15630051326')");
            count+=statement.executeUpdate("insert into `user` values(null, '猪八戒', '12345', '邯郸市邯山区邯郸大学','15630051326')");
            System.out.println("插入了" + count + "条记录");
            if(count>0){
                System.out.println("插入成功");
            }else {
                System.out.println("添加失败");
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e){
            e.printStackTrace();
        }finally{

            //避免空指针异常
            //1.释放sql语句执行对象
            if(statement!=null){
                try {
                    statement.close(); //内存泄露 垃圾回收不掉
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            //1.释放连接对象
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
